package com.simple.framework.core.auth;

import com.simple.framework.core.domain.BaseUser;
import com.simple.framework.core.domain.LoginUser;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

/**
 * @Description 认证上下文
 * @Author xiaoke
 * @Date 2024/8/10 18:00
 * @Version 1.0
 */
public class JwtContext {

    private static final ThreadLocal<LoginUser> tl = new ThreadLocal<>();

    /**
     * 获取登录用户
     *
     * @return 登录用户
     */
    public static LoginUser getLoginUser() {
        handlerIsNull();
        return tl.get();
    }

    /**
     * 获取登录用户id
     *
     * @return 登录用户id
     */
    public static Long getUserId() {
        handlerIsNull();
        return tl.get().getUser().getId();
    }

    public static void setUserId(Long userId) {
        LoginUser loginUser = tl.get();
        if(tl.get() == null) {
            loginUser = new LoginUser();
        }
        BaseUser baseUser = new BaseUser();
        baseUser.setId(userId);
        loginUser.setUser(baseUser);
        setLoginUser(loginUser);
    }

    /**
     * 获取登录用户名
     *
     * @return 登录用户名
     */
    public static String getUsername() {
        handlerIsNull();
        return tl.get().getUser().getUsername();
    }

    /**
     * 获取登录用户权限
     *
     * @return 登录用户权限
     */
    public static List<String> getPerms() {
        handlerIsNull();
        return tl.get().getPermissions();
    }

    /**
     * 设置登录用户信息
     *
     * @param user 用户信息
     */
    public static void setLoginUser(LoginUser user) {
        tl.set(user);
    }

    /**
     * 除了异步线程获取当前登录用户可能为空问题
     */
    private static void handlerIsNull() {
        if (tl.get() == null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            tl.set((LoginUser) principal);
        }
    }
}
